package thinking.in.spring.ioc.overview.dependency.lookup;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import thinking.in.spring.ioc.overview.annotation.Super;
import thinking.in.spring.ioc.overview.domain.User;

import java.util.Map;

/**
 * 依赖查找示例
 * 1. 通过名称的方式来查找
 *
 * @author Ringo
 * @date 2021/8/21 22:24
 */
public class DependencyLookupDemo {
    public static void main(String[] args) {
        // 配置 XML 文件
        // 启动 Spring Application Context
        String configLocation = "classpath:/META-INF/dependency-look-context.xml";
        BeanFactory beanFactory = new ClassPathXmlApplicationContext(configLocation);
        // 1: 实时查找bean
//        lookUpInRealTime(beanFactory);
        // 2: 延时查找bean
//        lookUpInLazy(beanFactory);
        // 3: 按类型查找bean
//        lookupByType(beanFactory);
        // 4: 按类型查找bean, 结果封装为集合
//        lookupCollectionByType(beanFactory);
        // 5: 按注解类型查找bean
        lookupByAnnotationType(beanFactory);
    }

    // 通过注解方式查找
    private static void lookupByAnnotationType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println(users);
        }
    }

    // 根据类型查找 Bean, 以集合的方式返回
    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有 User 集合对象: " + users);
        }
    }

    // 按照类型查找
    private static void lookupByType(BeanFactory beanFactory) {
        User user = beanFactory.getBean(User.class);
        System.out.println("按照类型查找: " + user);
    }

    // 延时查找
    private static void lookUpInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User user = objectFactory.getObject();
        System.out.println("延时查找: " + user);
    }

    // 实时查找
    private static void lookUpInRealTime(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时查找: " + user);
    }
}
